package com.woniu.zsd.permission.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.zsd.permission.mapper.RolesMapper;
import com.woniu.zsd.permission.mapper.RolesResourceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.fasterxml.jackson.core.type.TypeReference;

@Component
public class RoleResourceCacheUtil {

    @Autowired
    private RolesMapper rolesMapper;

    @Autowired
    private RolesResourceMapper rolesResourceMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 清理并重新加载角色资源缓存
     */
    public void reloadRoleResourcesCache() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 清理现有缓存
            deleteRoleResourcesCache();

            // 查询所有角色资源
            List<Map<String, Object>> allRolesResources = rolesResourceMapper.selectRolesResourceWithDetails();
            String allRolesResourcesJson = objectMapper.writeValueAsString(allRolesResources);
            redisTemplate.opsForValue().set("role:resources:all", allRolesResourcesJson);

            // 按角色名分组资源
            Map<String, List<Map<String, Object>>> groupedRolesResources = allRolesResources.stream()
                    .collect(Collectors.groupingBy(roleResource -> (String) roleResource.get("roleName")));

            // 分别为每种角色缓存其所有资源
            groupedRolesResources.forEach((roleName, roleResources) -> {
                if ("super_admin".equals(roleName) || "t_admin".equals(roleName) || "admin".equals(roleName)) {
                    String key = "role:resources:" + roleName;
                    String roleResourcesJson = null;
                    try {
                        roleResourcesJson = objectMapper.writeValueAsString(roleResources);
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException(e);
                    }
                    redisTemplate.opsForValue().set(key, roleResourcesJson);
                } else if ("user".equals(roleName)) {
                    // 为 user 角色缓存空权限
                    String key = "role:resources:user";
                    redisTemplate.opsForValue().set(key, "[]"); // 缓存空列表
                }
            });
        } catch (Exception e) {
            throw new RuntimeException("重新加载角色资源缓存失败", e);
        }
    }

    /**
     * 清理角色资源缓存
     */
    private void deleteRoleResourcesCache() {
        // 获取所有与角色资源相关的缓存键
        Set<String> keys = redisTemplate.keys("role:resources:*");

        // 删除这些缓存键
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
    }
}
